import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

const routerPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return routerPush.call(this, location).catch(error=> error)
}

//二级菜单需要隐藏的页面，加hidden: true, 不需要的不用加
Vue.use(VueRouter)
// 固定路由
let fixedRoutes = [
  {
    path:'/',
    redirect: '/order/orderList',
    hidden: true
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/index'),
    hidden: true
  },
  {
    path: '/bindWxLoading',
    name: 'bindWxLoading',
    component: () => import('@/views/gasStationManage/accountManage/bindWxloading'),
    hidden: true
  },
  {
    path: '/404',
    name: '404',
    component: () => import('@/views/noPermission/index'),
    hidden: true
  }
]
// 动态路由
let dynamicRoute = []

const routerContext = require.context('./', true, /index\.js$/)
routerContext.keys().forEach(route => {
  // 如何是根目录的 index.js 不处理
  if (route.startsWith('./index')) {
    return
  }
  const routerModule = routerContext(route)
  /**
   * 兼容 import export 和 require module.export 两种规范
   */
  dynamicRoute = [...dynamicRoute, ...(routerModule.default || routerModule)]
})

store.dispatch('permission/generateRoutes', dynamicRoute)

const createRouter = () => new VueRouter({
  mode: 'history',
  routes: fixedRoutes
})

const router = createRouter()

export function resetRouter () {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher
}

export default router
